#include "widget.h"
#include "./ui_widget.h"
#include <QTableWidget>
#include <QDateTime>

Widget::Widget(QWidget *parent,const QString& host_username,const QString& last_time)
    : QWidget(parent)
    , ui(new Ui::Widget)
    ,socket(new QTcpSocket)
    ,host_username(host_username)
    ,host_last_time(last_time)
{
    ui->setupUi(this);
    this->socket->connectToHost(QHostAddress("101.201.74.27"),8888);

    //处理信号
    connect(this->socket,&QTcpSocket::connected,this,&Widget::SendLinkSuccessMsg);
    connect(this->socket,&QTcpSocket::readyRead,this,&Widget::ReceiveMsg);

}

Widget::~Widget()
{
    delete ui;
}

void Widget::closeEvent(QCloseEvent *)
{
    emit(this->closeWidget());
}

void Widget::on_sendBtn_clicked()
{
    QString msg=ui->msgTxtEdit->toPlainText();
    ui->msgTxtEdit->clear();
    bool res=DatabaseManager::getInstance().PrivateSendMsg(this->host_username,this->username,msg);
    QDateTime current_time=QDateTime::currentDateTime();
    qDebug()<<"发送框内消息";
    if(!res)
    {
         ui->msgBrowser->append("普通聊天两人一共最多6次机会");
        return ;
    }
    this->socket->write(msg.toUtf8());
    ui->msgBrowser->append(this->host_username+":"+current_time.toString()+":"+msg);
}

void Widget::SendLinkSuccessMsg()
{
    qDebug()<<"连接目标主机成功";
    QString s("你好，服务器，我是客户端");

    this->socket->write(s.toUtf8());
}

void Widget::ReceiveMsg()
{
    QVector<QString> res=DatabaseManager::getInstance().PrivateGetMsg(this->username,this->host_username,this->host_last_time);
    for(const QString& tmp :res)
    {
        ui->msgBrowser->append(this->nickname+":"+tmp);
    }
    // while(socket->bytesAvailable()>0)
    // {
    //     QByteArray chunk=socket->read(1024);
    //     QString text=QString::fromUtf8(chunk);
    //     text = text.remove(QRegularExpression("[^\u0000-\uFFFF]")); // 移除不可见字符
    //     ui->msgBrowser->append(text);

    // }

}

void Widget::set_basement(const QString &username, const QString &nickname)
{
    this->username=username;this->nickname=nickname;
    QTableWidget *tableWidget=ui->widget_7->findChild<QTableWidget*>();
    tableWidget->setItem(tableWidget->rowCount()-1,0,new QTableWidgetItem(this->username));        // 假设第一列存用户名
    tableWidget->setItem(tableWidget->rowCount()-1,1,new QTableWidgetItem(this->nickname)); // 假设第二列存昵称
    ReceiveMsg();
}

